<template>
	<section>
		<el-row v-if="fields.length>0"> 
 			<!--新增界面 FormData 表单数据表--> 
			<el-form :model="editForm" :label-width="labelWidthCpd" :label-position="labelPosition" :show-message="true" :rules="editFormRules" ref="editForm"> 
				<el-col :span="spanCalc(item)" v-for="(item,index) in fields" :key="index"> 
					<span  v-if="item.nr"></span>
					<el-form-item v-else :label="item.fieldTitle" :prop="item.fieldIdCamel">  
						<div  v-if="item.nr"></div>
					<!--用户-->
						<mdp-select-user v-else-if=" item.extFieldType=='user'" :show-style="item.showStyle" :disabled="item.ne" :multiple="item.isMultiple=='1'" v-model="editForm[item.fieldIdCamel]" :label-width="labelWidthCpd" :label="item.fieldTitle"  :placeholder="item.placeholder"  split="," @change="(e)=>onFieldChange(e,item)">			 
						</mdp-select-user>  
					<!--部门-->
						<mdp-selecct-dept v-else-if=" item.extFieldType=='deppt'" :show-style="item.showStyle" :disabled="item.ne" :branch-id="userInfo.branchId" :show-checkbox="item.isMultiple=='1'" :multiple="item.isMultiple=='1'" split="," @change="(e)=>onFieldChange(e,item)"></mdp-selecct-dept>

					<!--标签-->
						<mdp-select-tag  v-else-if=" item.extFieldType=='tag'" :show-style="item.showStyle" :disabled="item.ne" :multiple="item.isMultiple=='1'" v-model="editForm[item.fieldIdCamel]" :label-width="labelWidthCpd" :label="item.fieldTitle"  :placeholder="item.placeholder"  split="," @change="(e)=>onFieldChange(e,item)">			 
						</mdp-select-tag>  
					<!--下拉框-->
						<mdp-select v-else-if=" ['select','radio','checkbox'].some(k=>k==item.fieldType)"  :show-style="item.showStyle" :disabled="item.ne" :show-type="item.fieldType"  :item-code="item.dictCode" :multiple="item.isMultiple=='1'" v-model="editForm[item.fieldIdCamel]" :label-width="labelWidthCpd" :label="item.fieldTitle"  :placeholder="item.placeholder" split="," @change="(e)=>onFieldChange(e,item)">			 
						</mdp-select>
					<!--html-->
						<el-popover v-else-if=" item.extFieldType=='html'"
							placement="top-start"
							width="400"
							trigger="hover">
							<el-input  type="textarea" rows="4" v-model="editForm[item.fieldIdCamel]" :disabled="item.ne" @change="(e)=>onFieldChange(e,item)"></el-input>
							<div slot="reference"  v-html="editForm[item.fieldIdCamel]||item.defaultValue||'无'"></div>
						</el-popover>
					<!--link 链接-->
						<el-popover v-else-if=" item.extFieldType=='link'"
							placement="top-start"
							width="400"
							trigger="hover">
							<el-input v-model="editForm[item.fieldIdCamel]" :disabled="item.ne" @change="(e)=>onFieldChange(e,item)"></el-input>
 							<el-link slot="reference" :href="editForm[item.fieldIdCamel]" target="_blank">{{ editForm[item.fieldIdCamel]||item.fieldTitle }}</el-link> 
						</el-popover>
					<!--image-->
						<el-popover v-else-if=" item.extFieldType=='image'"
							placement="top-start" 
							trigger="hover">
							<el-button  @click="$refs['imageDialog'].open({formData:editForm,item:item})" :disabled="item.ne">上传图片</el-button> 
							<el-image slot="reference"  :style="item.styleObj||{maxHeight:'100px',maxWidth:'100px'}"
								:src="editForm[item.fieldIdCamel]"
								fit="contain" >
							</el-image>
 						</el-popover>
					<!--att 附件-->
						<el-popover v-else-if=" item.extFieldType=='att'"
							placement="top-start" 
							trigger="hover">
							<el-button  @click="$refs['attDialog'].open({formData:editForm,item:item})" :disabled="item.ne">上传附件</el-button> 
 							<el-link slot="reference" :href="editForm[item.fieldIdCamel]" target="_blank">{{ editForm[item.fieldIdCamel]||item.fieldTitle }}</el-link> 
						</el-popover>
					<!--其它类型-->
						<mdp-input :show-style="item.showStyle"  :disabled="item.ne" v-else-if="item.fieldType=='text'" style="width: 90%;"  v-model="editForm[item.fieldIdCamel]" :label-width="labelWidthCpd" :label="item.fieldTitle" auto-complete="off" :placeholder="item.placeholder"  clearable @change="(e)=>onFieldChange(e,item)"> </mdp-input>
 						<mdp-number :show-style="item.showStyle" :disabled="item.ne"   v-else-if="item.fieldType=='number'"  v-model="editForm[item.fieldIdCamel]" :label-width="labelWidthCpd" :label="item.fieldTitle" auto-complete="off"  placeholder="请输入内容"  clearable @change="(e)=>onFieldChange(e,item)"></mdp-number>
						<mdp-number :show-style="item.showStyle" :disabled="item.ne"   v-else-if="item.fieldType=='amount'"  v-model="editForm[item.fieldIdCamel]" :label-width="labelWidthCpd" :label="item.fieldTitle" auto-complete="off"  placeholder="请输入内容"  clearable @change="(e)=>onFieldChange(e,item)"></mdp-number>
						<mdp-input :show-style="item.showStyle" :disabled="item.ne"   v-else-if="item.fieldType=='textarea'"   type="textarea" :rows="2" v-model="editForm[item.fieldIdCamel]" :label-width="labelWidthCpd" :label="item.fieldTitle"  placeholder="请输入内容" @change="(e)=>onFieldChange(e,item)"></mdp-input>
						<el-time-picker :show-style="item.showStyle" :disabled="item.ne"   v-else-if="item.fieldType=='time'"   v-model="editForm[item.fieldIdCamel]"  placeholder="任意时间点" value-format="HH:mm:ss" format="HH:mm:ss" @change="(e)=>onFieldChange(e,item)"> </el-time-picker> 
						<mdp-date :show-style="item.showStyle" :disabled="item.ne"   v-else-if="item.fieldType=='date'"  v-model="editForm[item.fieldIdCamel]" align="right" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="选择日期" :picker-options="pickerOptions" @change="(e)=>onFieldChange(e,item)"> </mdp-date>
						<mdp-date :show-style="item.showStyle" :disabled="item.ne" v-else-if="item.fieldType=='datetime'"  v-model="editForm[item.fieldIdCamel]" type="datetime"  value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间" align="right" :picker-options="pickerOptions" @change="(e)=>onFieldChange(e,item)"> </mdp-date>
						<mdp-date :show-style="item.showStyle" :disabled="item.ne" v-else-if="item.fieldType=='month'"  v-model="editForm[item.fieldIdCamel]" type="month" value-format="yyyy-MM" format="yyyy-MM" placeholder="选择月份" @change="(e)=>onFieldChange(e,item)"></mdp-date>
						<mdp-date :show-style="item.showStyle" :disabled="item.ne" v-else-if="item.fieldType=='year'"  v-model="editForm[item.fieldIdCamel]" type="month" value-format="yyyy" format="yyyy" placeholder="选择年" @change="(e)=>onFieldChange(e,item)"></mdp-date>
						<mdp-date-range :show-style="item.showStyle" :disabled="item.ne"   v-else-if="item.fieldType=='daterange'"  :value="editForm[item.fieldIdCamel]?editForm[item.fieldIdCamel].split(','):[]" align="right" type="daterange" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="选择日期" :picker-options="pickerOptions" @change="(vs)=>{editForm[item.fieldIdCamel]=vs.join(',');onFieldChange(vs)}"> </mdp-date-range>  
					</el-form-item>        
				</el-col>
			</el-form> 
		</el-row>
		
		<slot>
			<el-row class="footer"> 
				<el-button @click.native="handleCancel">关闭</el-button>  
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>   
			</el-row> 
		</slot>

		
		<mdp-dialog ref="imageDialog" title="选择图片" width="80%" :modal="false">
			<template v-slot="{visible,data,dialog}">
				<mdp-select-image v-if="visible" :visible="visible" @select="(imgs)=>{
					if(data.item.isMultiple=='1'){
						data.formData[data.item.fieldIdCamel]=imgs&&imgs.length>0?imgs.map(i=>i.url).join(','):null
					}else{
						data.formData[data.item.fieldIdCamel]=imgs&&imgs.length>0?imgs[0].url:null
					}
					dialog.close();
				}"></mdp-select-image>
			</template> 
		</mdp-dialog>  
		<mdp-dialog ref="attDialog" title="选择文件" width="80%" :modal="false">
			<template v-slot="{visible,data,dialog}">
				<mdp-select-att v-if="visible" :visible="visible" :multiple="data.item.isMultiple=='1'" @select="(imgs)=>{ 
					if(data.item.isMultiple=='1'){
						data.formData[data.item.fieldIdCamel]=imgs&&imgs.length>0?imgs.map(i=>i.url).join(','):null
					}else{
						data.formData[data.item.fieldIdCamel]= (imgs?imgs.url:null)
					}
					 
					 dialog.close();
				}" split=","></mdp-select-att>
			</template> 
		</mdp-dialog>  
	</section>
</template>

<script> 
	import { mapGetters } from 'vuex'  
	/**
	 * 表单数据填单
	 */
	export default { 
	    computed: {
		    ...mapGetters([
		      'userInfo','roles','myDepts'
			]),
			labelWidthCpd:function(){
				if(this.labelWidth){
					return this.labelWidth
				}
				return this.labelWidthCalc();
			},
			fieldsCpd:function(){
				var formFields=this.formFields?this.formFields:[]
				formFields.forEach(k=>{			//权限控制
					this.initFieldQx(k)  
				})
				return formFields
			}
		},
		props:{
			visible:{type:Boolean,default:false},
			value:{type:Object,default:null},
			formDef:{type:Object,default:null},
			formFields:{type:Array,default:null}, 
			labelWidth:{type:String,default:null},			
			labelPosition:{type:String,default:null},
		
		},
		watch: {
			value:function(){
				this.initData()
			}, 
			'formFields':function(formFields) {  
				this.initByFormFields()
			},  
	    },	
		data() {
			return {
				
				filters:{
					users:[]
				},
				pickerOptions: this.$mdp.getPickerOptions(),

				editLoading: false,
				editFormRules: {
					 
				},
				//新增界面数据 表单数据表
				editForm: {
  				},  
				//最原始的数据，用于与最新的editForm比较，获得修改日志
				editFormBak:null,
				fields:[],
				/**end 在上面加自定义属性**/
			}//end return
		},//end data
		methods: {
			// 取消按钮点击 父组件监听@cancel="editFormVisible=false" 监听
			handleCancel:function(){
				this.$emit('cancel');
			},
			labelWidthCalc:function(){
				if (screen.width <=375){
					return "80px"
				}else  if (screen.width <= 500){
						return "80px"
				}else if (screen.width<=1024){
						return "100px"
				}else {
						return "120px"
				}
			} , 
			spanCalc:function(item){
				var span=screen.width>500?12:24
				if(item.fieldType=="textarea"){
					span=24;
				}
				return span;
			}, 
			//新增提交FormData 表单数据表 父组件监听@submit="afterAddSubmit"
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) { 
							this.editLoading = true;  
							let params = Object.assign({}, this.editForm); 
							if(params.formId==null || params.formId==''){
								params.formId=this.formDef.id
							}
							params.userid=this.userInfo.userid
							if(!params.branchId){
								params.branchId=this.userInfo.branchId
							}
							if(!params.cuserid){
								params.cuserid=this.userInfo.userid
							}
							
							if(!params.cusername){
								params.cusername=this.userInfo.username
							} 
							if(!params.deptid){
								params.deptid=this.userInfo.deptid
							} 
							if(!params.deptName){
								params.deptName=this.userInfo.deptName
							} 
							var bizKeys=[];
							if(this.formFields!=null && this.formFields.length>0){
								var isBizKey=this.formFields[0].isBizKey;
								if(isBizKey && isBizKey.length==3){
									if(isBizKey.charAt(0)=="1"){
										 bizKeys.push(params.cuserid);
									} 
									if(isBizKey.charAt(1)=="1"){
										 bizKeys.push(params.deptid);
									} 
								}
							}
 							this.formFields.forEach(item=>{ 
								if(item.isBizKey.charAt(2)=="1"){
									bizKeys.push(params[item.fieldIdCamel]);
								}
								if(params[item.fieldIdCamel]!=this.editForm[item.fieldIdCamel]){
									params.changeData=true;
								}
							
							});
							if(bizKeys.length==0){
								if(params.id){
									bizKeys.push(params.id);
								}
								
							}
							if(bizKeys.length>0){
								params.bizKey=bizKeys.join(","); 
							}
							this.$emit('input',params)
							this.$emit('submit',params);//  @submit="afterAddSubmit"  
					}
				}); 
			}, 
			/**end 在上面加自定义方法**/
			onFieldChange(val,field){ 
				if(!this.editFormBak){
					this.editFormBak={...this.value}
				}  
 				this.$nextTick(()=>{
					this.$refs.editForm.validateField([field.fieldIdCamel])
				})
				this.$nextTick(()=>{
					this.$emit('input',this.editForm)
					this.$emit('change',this.editForm,this.getChangeLogs())
				})
				
			},
			initByFormFields(){ 
				this.initData();
				this.formFields.forEach(item=>{ 
					if(item.isRequired=='1' ){
						this.editFormRules[item.fieldIdCamel]=[{ required: true, message: item.fieldTitle+'不能为空', trigger: 'blur' }] 
 					}   
					this.initFieldQx(item) 
				});
				this.fields=this.formFields
				this.$nextTick(()=>{
					this.$refs['editForm'].clearValidate();
				}) 
				
				
			},
			initFieldQx(item){ 
				
				var myUserid=this.userInfo.userid
				var myDeptids=this.myDepts?this.myDepts.map(d=>d.deptid):[]
				var myRoleids=this.roles?this.roles.map(r=>r.roleid):[]
				var myDataLvl=this.userInfo.maxDataLvl
				if(item.fieldQx){ 
					
					item.nr=false
					item.ne=false
					var fieldQx=JSON.parse(item.fieldQx)
					if(!fieldQx.othQuery){
						item.nr=false
					}else if(fieldQx.othQuery=='0'){
						item.nr=true
						item.ne=true
					}else if(fieldQx.othQuery=='1'){
						if(item.qryMinLvl && myDataLvl<item.qryMinLvl){
							item.nr=true
							item.ne=true
						}else{
							var qryUserids=fieldQx.qryUserids?fieldQx.qryUserids.split(","):[]
							var qryDeptids=fieldQx.qryDeptids?fieldQx.qryDeptids.split(","):[]
							var qryRoleids=fieldQx.qryRoleids?fieldQx.qryRoleids.split(","):[] 
							if(qryUserids.some(u=>u==myUserid)){
								item.nr=false
							}
							 if(qryDeptids.some(u=>u==myDeptids.some(d=>d==u))){
								item.nr=false
							}
							if(qryRoleids.some(r=>myRoleids.some(mr=>mr==r))){
								item.nr=false
							}
							
							var nqUserids=fieldQx.nqUserids?fieldQx.nqUserids.split(","):[]
							var nqDeptids=fieldQx.nqDeptids?fieldQx.nqDeptids.split(","):[]
							var nqRoleids=fieldQx.nqRoleids?fieldQx.nqRoleids.split(","):[] 
							if(nqUserids.some(u=>u==myUserid)){
								item.nr=true
								item.ne=true
							}else if(nqDeptids.some(d=>myDeptids.some(k=>k==d))){
								item.nr=true
								item.ne=true
							}else if(nqRoleids.some(r=>myRoleids.some(mr=>mr==r))){
								item.nr=true
								item.ne=true
							}
						}
						
					}
					if(item.editMinLvl && myDataLvl<item.editMinLvl){
 						item.ne=true
					}else{
						if(!fieldQx.othEdit){
							item.ne=false
						}else if(fieldQx.othEdit=='0'){ 
							item.ne=true
						}else if(fieldQx.othEdit=='1'){
							var editUserids=fieldQx.editUserids?fieldQx.editUserids.split(","):[]
							var editDeptids=fieldQx.editDeptids?fieldQx.editDeptids.split(","):[]
							var editRoleids=fieldQx.editRoleids?fieldQx.editRoleids.split(","):[] 
							if(editUserids.some(u=>u==myUserid)){
								item.ne=false
							}
							if(editDeptids.some(d=>myDeptids.some(k=>k==d))){
								item.ne=false
							}
							if(editRoleids.some(r=>myRoleids.some(mr=>mr==r))){
								item.ne=false
							}
							
							var neUserids=fieldQx.neUserids?fieldQx.neUserids.split(","):[]
							var neDeptids=fieldQx.neDeptids?fieldQx.neDeptids.split(","):[]
							var neRoleids=fieldQx.neRoleids?fieldQx.neRoleids.split(","):[] 
							if(neUserids.some(u=>u==myUserid)){ 
								item.ne=true
							}else if(neDeptids.some(d=>myDeptids.some(k=>k==d))){ 
								item.ne=true
							}else if(neRoleids.some(r=>myRoleids.some(mr=>mr==r))){ 
								item.ne=true
							}
						}
					}

				}else{
					item.nr=false
					item.ne=false
				}
				this.$set(item,'nr',item.nr)
				this.$set(item,'ne',item.ne)

			},
			//[log1,log2],其中log1={fieldId:'字段编号',oldVal:'原值',currVal:'修改后的值',fieldTitle:'字段名称'}
			getChangeLogs(){ 
				if(this.editFormBak==null){
					return null
				}else{
					var keys=Object.keys(this.editForm)
					var changeLogs=[]
					keys.forEach(key=>{
						var field=this.formFields.find(k=>k.fieldIdCamel==key)
						if(field){
							var oldVal=this.editFormBak[key]
							var currVal=this.editForm[key] 
							var log={}
							if((currVal!=oldVal && ( currVal || oldVal ))){
								if(!oldVal && currVal=='0'){

								}else{
									log={fieldId:field.fieldIdCamel,fieldTitle:field.fieldTitle,oldVal:oldVal,currVal:currVal}
									changeLogs.push(log)
								}
								
							}
							
						}
					})
					return changeLogs;
				}
			},
			initData(){
				
				if(this.value){
					this.editForm=Object.assign({},this.value)
				}else{
					this.editForm={}
				}
			}
		},//end method
		components: {   
		},
		mounted() {    
			this.initData(); 
			this.$nextTick(()=>{
				this.initByFormFields(); 
			})
			
			
			
  
			
		}//end mounted
	}

</script>

<style scoped>

</style>